'use strict'

import { qiniu, cloudinary } from '../../config/config'
import robot from '../service/robot'
import Promise from 'bluebird'

import mongoose from 'mongoose'
const Video = mongoose.model('Video')
const Audio = mongoose.model('Audio')

const asyncMedia = (videoId, audioId) => {
  console.log('检查数据有效性')
  if (!videoId) return

  let query = {
    _id: audioId
  }

  if (!audioId) {
    query = {
      video: videoId
    }
  }

  Promise.all([
    Video.findOne({ _id: videoId }).exec(),
    Audio.findOne(query).exec()
  ])
    .then(data => {
      let video = data[0]
      let audio = data[1]

      if (!video || !video.public_id || !audio || !audio.public_id) return

      console.log('开始同步音视频')
      const video_public_id = video.public_id
      const audio_public_id = audio.public_id
      const videoName = video_public_id.replace('/', '_') + '.mp4'
      const videoUrl = 'https://res.cloudinary.com/' + cloudinary.cloud_name + '/video/upload/e_volume:-100/e_volume:400,l_video:' + audio_public_id.replace(/\//g, ':') + '/' + video_public_id + '.mp4'
      const thumbName = video_public_id.replace('/', '_') + '.jpg'
      const thumbUrl = 'https://res.cloudinary.com/' + cloudinary.cloud_name + '/video/upload/' + video_public_id + '.jpg'

      console.log('同步视频到七牛')
      robot
        .saveToQiniu(videoUrl, videoName)
        .catch(error => {
          console.log(error)
        })
        .then(response => {
          if (response) {
            audio.qiniu_video = response.key
            audio.save()
            console.log('同步视频到七牛成功')
          }
        })

      console.log('同步封面图到七牛')
      robot
        .saveToQiniu(thumbUrl, thumbName)
        .catch(error => {
          console.log(error)
        })
        .then(response => {
          if (response) {
            audio.qiniu_thumb = response.key
            audio.save()
            console.log('同步封面图到七牛成功')
          }
        })
    })

}

exports.video = async (ctx, next) => {
  const body = ctx.request.body
  const videoData = body.video
  let user = ctx.session.user

  if (!videoData || !videoData.key) {
    ctx.body = {
      success: false,
      err: '视频没有上传成功！'
    }

    return next
  }

  let video = await Video.findOne({
    qiniu_key: videoData.key
  }).exec()

  if (!video) {
    video = new Video({
      author: user._id,
      qiniu_key: videoData.key,
      persistentId: videoData.persistentId
    })

    video = await video.save()
  }


  const url = qiniu.video + video.qiniu_key

  robot
    .uploadToCloudinary(url)
    .then(data => {
      console.log(data)
      if (data && data.public_id) {
        video.public_id = data.public_id
        video.detail = data

        video.save().then(video => {
          asyncMedia(video._id)
        })
      }
    })

  ctx.body = {
    success: true,
    data: video._id
  }
}

exports.audio = async (ctx, next) => {
  const body = ctx.request.body
  const audioData = body.audio
  const videoId = body.videoId
  let user = ctx.session.user

  if (!audioData || !audioData.public_id) {
    ctx.body = {
      success: false,
      err: '音频没有上传成功！'
    }

    return next
  }

  let audio = await Audio.findOne({
    public_id: audioData.public_id
  }).exec()

  let video = await Video.findOne({
    _id: videoId
  }).exec()

  if (!audio) {
    audio = new Audio({
      author: user._id,
      public_id: audioData.public_id,
      detail: audioData
    })

    if (video) {
      audio.video = video._id
    }

    audio = await audio.save()
  }

  //异步操作
  asyncMedia(video._id, audio._id)

  ctx.body = {
    success: true,
    data: audio._id
  }
}

exports.save = async (ctx, next) => {
  const body = ctx.request.body
  const videoId = body.videoId
  const audioId = body.audioId
  const title = body.title

  ctx.body = {
    success: true
  }
}

